<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'error: requests are not allowed']);
    exit;
}
require($_SERVER['DOCUMENT_ROOT'].'/cofd/common.php');
$id = $_POST['id'];
$field = isset($_POST['field']) ? trim($_POST['field']) : '';
$value = isset($_POST['value']) ? trim($_POST['value']) : '';
$allowedFields = ['used', 'canuse', 'vips', 'words'];
if (!in_array($field, $allowedFields)) {
    echo json_encode(['code' => 1, 'message' => '不允许更新该字段']);
    exit;
}
if (in_array($field, ['used', 'canuse', 'vips'])) {
    $value = floatval($value);
} else {
    $value = $conn->real_escape_string($value);
}
try {
    if (!$conn->real_escape_string($field)) {
        echo json_encode(['code' => 1, 'message' => '字段名无效']);
        exit;
    }
    $sql = "UPDATE cdk SET `$field` = ? WHERE cdk = ?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['code' => 1, 'message' => 'SQL错误：' . $conn->error]);
        exit;
    }
    if (in_array($field, ['used', 'canuse', 'vips'])) {
        $stmt->bind_param('is', $value, $id);
    } else {
        $stmt->bind_param('ss', $value, $id);
    }
    $stmt->execute();
    if ($stmt->affected_rows > 0) {
        echo json_encode(['code' => 0, 'message' => '更新成功']);
    } else {
        echo json_encode(['code' => 1, 'message' => '未找到CDK或无更新']);
    }
    $stmt->close();
    $conn->close();
} catch (Exception $e) {
    echo json_encode(['code' => 1, 'message' => '数据库错误：' . $e->getMessage()]);
}
?>